# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""
import matplotlib.pyplot as plt
import matplotlib.image as mping
import numpy as np
import math
import os
import pylab
import hashlib
import sys
import string
import imghdr
from PIL import Image
from PIL import ImageFile
###防止图片数据被截断的预处理
ImageFile.LOAD_TRUNCATED_IMAGES = True

###列举出文件夹里面包括的所有图片类型文件
def eachFile(filepath):
    filelist2=[]
    pathDir = os.listdir(filepath)
    pathDir_pic=[]
    for files in pathDir:
        pathDir_pic.append(os.path.splitext(files)[0])
    for allDir in pathDir:
        child = os.path.join('%s%s%s' % (filepath,'/', allDir))
        filelist2.append(child)
       # .decode('gbk')是解决中文显示乱码问题
    return filelist2,pathDir_pic
###由读取到的图片原始信息转换成我们需要的颜色指标信息
def get_indicator(file):
        try:  
            rgb=mping.imread(file)
            data1=[[0.299,0.587,0.114],[0.596,-0.274,-0.322],[0.212,-0.523,-0.311]]
            width=rgb.shape[0]
            height=rgb.shape[1]
            dim=rgb.shape[2]
            global resultYIQ,resultYCbCr
            resultYIQ=np.zeros([width,height,dim])
            for i in range(3):
                resultYIQ[:,:,i]=rgb*np.matrix(data1[i]).T
            data2=[[0.299,0.587,0.114],[-0.169,-0.331,0.5],[0.5,-0.419,-0.081]]
            addt=[16,128,128]
            resultYCbCr=np.zeros([width,height,dim])
            for j in range(3):
                resultYCbCr[:,:,j]=rgb*np.matrix(data2[i]).T+addt[i]
        except IndexError:
            pass    
        return resultYIQ,resultYCbCr
#==============================================================================
# #    resultHSV=np.zeros([width,height,dim])
# #    for i in range(width):
# #        for j in range(height):
# #            I=0.596*test[i,j][0]+(-0.274*test[i,j][1])+(-0.322*test[i,j][2])
# #            resultHSV[i,j][2]=max(test[i,j])
# #            resultHSV[i,j][1]=1-(3*min(test[i,j])/I)
# #            if test[i,j][2]>test[i,j][1]:
# #                temp1=test[i,j][0]-test[i,j][1]+test[i,j][0]-test[i,j][2]
# #                temp=math.acos(temp1/(2*math.sqrt(pow(test[i,j][0]-test[i,j][1],2)+(test[i,j][0]-test[i,j][2])*(test[i,j][1]-test[i,j][2]))))
# #                resultHSV[i,j][0]=2-temp
# #            else:
# #                temp1=test[i,j][0]-test[i,j][1]+test[i,j][0]-test[i,j][2]
# #                temp=math.acos(temp1/(2*math.sqrt(pow(test[i,j][0]-test[i,j][1],2)+(test[i,j][0]-test[i,j][1])*(test[i,j][1]-test[i,j][2]))))
# #                resultHSV[i,j][0]=temp
# #    return resultYIQ,resultYCbCr,resultHSV
#==============================================================================
###判断每个区域的像素的索引是否超出提取的整张图片的索引
def judge_dim(rgb,area_point):
    resultlist=[]
    for i in range(len(area_point)):
        if area_point[i][0]<rgb.shape[0] and area_point[i][1]<rgb.shape[1]:
           resultlist.append(area_point[i])        
    return resultlist

###将原有的二维特征进行一维展开
def two_conversion_one(indicator):
    List1=[]
    List2=[]
    List3=[]
    for i in range(len(indicator)):
            List1.append(indicator[i][0])
            List2.append(indicator[i][1])
            List3.append(indicator[i][2])
    return List1,List2,List3

###计算特征的统计特性，主要有四个,平均，标准差,最小值，最大值
def statistics(indicator):
    dataset=two_conversion_one(indicator)
    statis=[]
#    mean_1=np.array(dataset[0]).mean()
#    std_1=np.array(dataset[0]).std()
#    min_1=np.array(dataset[0]).min()
#    max_1=np.array(dataset[0]).max()
#    skew_1=np.array(dataset[0]).skew()     
    for i in range(3):
        try:
             statis.append(np.array(dataset[i]).mean())
             statis.append(np.array(dataset[i]).std())
             statis.append(np.array(dataset[i]).min())
             statis.append(np.array(dataset[i]).max())
        except ValueError:
            pass
    return statis

###判断图片类型并且返回
def pic_type_judge(imagefile):
    imgtype=imghdr.what(imagefile)
    return imgtype 

####根据图片的真实后缀类型把图片重新命名
def reanme():
    path="D:\\output\\output"
    count=0;
    filelist=os.listdir(path)
    for files in filelist:
        Olddir=os.path.join(path,files)
        reatype=pic_type_judge(Olddir)
        if os.path.isdir(Olddir):
            continue;
        filename=os.path.splitext(files)[0];
        filetype=os.path.splitext(files)[1];
        Newdir=os.path.join(path,filename+'.'+reatype);
        os.rename(Olddir,Newdir);
        count+=1;
    

####计算对应区域的指标特征，YIQ,YCbCr特征
def correspond_indicator(area_point,picfile):   
    resultYIQ,resultYCbCr=get_indicator(picfile)
    rgb=mping.imread(picfile)
    resultlist=judge_dim(rgb,area_point)    
    YIQ_indicator=[]
    #HSV_indicator=[]
    YCbCr_indicator=[]
    try:
        for i in range(len(resultlist)):
             YIQ_indicator.append(resultYIQ[resultlist[i][0],resultlist[i][1]])
             #HSV_indicator.append(resultHSV[resultlist[i][0],resultlist[i][1]])
             YCbCr_indicator.append(resultYCbCr[resultlist[i][0],resultlist[i][1]])
    except IndexError:
        pass             
    YIQ_statis=statistics(YIQ_indicator)
    YCbCr_statis=statistics(YIQ_indicator)
    return YIQ_statis,YCbCr_statis 
  


  
#def statistics(indicator):
#    dataset=two_conversion_one(indicator)
#    statis=[]
##    mean_1=np.array(dataset[0]).mean()
##    std_1=np.array(dataset[0]).std()
##    min_1=np.array(dataset[0]).min()
##    max_1=np.array(dataset[0]).max()
##    skew_1=np.array(dataset[0]).skew()     
#    for i in range(3):
#         statis.append(np.array(dataset[i]).mean())
#         statis.append(np.array(dataset[i]).std())
#         statis.append(np.array(dataset[i]).min())
#         statis.append(np.array(dataset[i]).max())
#    return statis
       
            
#def draw_hist(data):
#    dataset=two_conversion_one(data)
#    pylab.hist(dataset[0],len(data))  #第一个指标频率分布图形
#    pylab.hist(dataset[1],len(data))  #第二个指标频率分布图形
#    pylab.hist(dataset[2],len(data))  #第三个指标频率分布直方图
#对身份证号码进行md5加密                   
def md5(s):  
    m = hashlib.md5()   
    m.update(s.encode('utf8'))
    return m.hexdigest()
  



                           
        